from datetime import datetime, timedelta, timezone
import re
from collections import namedtuple, defaultdict, deque, OrderedDict, Counter
import base64
import struct
import os
import hashlib
import itertools
from urllib import request

# datetime
now = datetime.now()
print(now)
print(now.timestamp())
print(datetime.fromtimestamp(now.timestamp()))
print(datetime.strftime(now, "%Y-%m-%d %H:%M:%S"))
print(datetime.strptime("2018-05-31 22:11:11", "%Y-%m-%d %H:%M:%S"))
print(now + timedelta(hours=1) + timedelta(days=1) - timedelta(seconds=20))
# 时区
utcnow = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utcnow)
print(utcnow.astimezone(timezone(timedelta(hours=8))))


# 练习
def to_timestamps(time_str, zone_str):
    zone = timezone(timedelta(hours=int(re.match(r"UTC([\+\-]{1}\d+):00",
                                                 zone_str).group(1))))
    return datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S"
                             ).replace(tzinfo=zone).timestamp()


result = to_timestamps(datetime.strftime(now, "%Y-%m-%d %H:%M:%S"), "UTC+8:00")
print(result)

# collections
# namedtruple
Point = namedtuple("Point", ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
# deque 双向列表，适用队列和栈, 头尾插入
de = deque(['1', '2', '3'])
de.append("4")
de.insert(1, '1.5')
de.appendleft("0")
print(de)
# defaultDict 提供不存在时的默认值，必须为函数
dd = defaultdict(lambda: None)
print(dd['xxx'])
# OrderedDict 有序 按照插入的顺序，而不是key本身的顺序
od = OrderedDict({'a': 1, "c": 3, "b": 2})
print(od)
# Counter 计数器 是特殊的dict
c = Counter()
for s in "sadbjdaiadjov asd[kascasck]":
    c[s] = c[s] + 1
print(c)


# base64  只能转byte数据，字符串需要先转换成bytes
b = "ada v 大尺度+".encode("utf8")
print(b)
print(base64.b64encode(b))
print(base64.urlsafe_b64encode(b))  # 将+和/转换成-和_


# 练习
def safe_decode_bytes(encodeStr):
    last = len(encodeStr.encode("utf-8")) % 4
    if last > 0:
        for i in range(4 - last):
            encodeStr += "="
    return base64.b64decode(encodeStr)


print(safe_decode_bytes("YWJjZA"))


# struct 处理其他二进制数据与字节之间的转换
# https://docs.python.org/3/library/struct.html#format-characters
print(struct.pack(">I", 124590))
print(type(struct.unpack('>IH', b'\xf0\xf0\xf0\xf0\x80\x80')))


def checkBmp(path):
    if not os.path.isfile(path):
        print("不是文件")
        return
    with open(path, 'rb') as f:
        bmpByte = f.read(30)
        up = struct.unpack("<ccIIIIIIHH", bmpByte)
        if up[0] == b'B' and up[1] == b'M':
            print("图片大小为%dx%d，颜色数为%d" % (up[6], up[7], up[9]))
            return
        else:
            print("不是bmp文件")
            return


checkBmp('E:\\pengxj\\工作\\其他\\学习\\python\\module\\1.bmp')


# 摘要算法 MD5 SHA1等
db = {}


def register(username, password):
    db[username] = get_md5(username, password)


def get_md5(username, password):
    md5 = hashlib.md5()
    md5.update((password + username + '盐').encode('utf8'))
    return md5.hexdigest()


register("dean", '123456')
register('pengxj', '123456')
print(db)

# itertools
# for x in itertools.count(100):
#    print(x)

# for x in itertools.cycle({'a', 'b', 'c'}):
#    print(x)

for x in itertools.repeat(['a', 'b', 'c'], 1):
    print(x)

for x in itertools.chain(['a', 'b', 'c'], {'a', 'b', 'c'}):
    print(x)


def checkType(x):
    return type(x)


for key, group in itertools.groupby([1, 2, 3, 4, 5,
                                     'a', 'b', 'c', 1], checkType):
    print(key, list(group))

# urllib
with request.urlopen("https://xqn.njlime.com/demo/tapp/contactAdmin") as f:
    data = f.read()
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', data.decode('utf-8'))
req = request.Request("https://xqn.njlime.com/demo/tapp/contactAdmin")
req.add_header('User-Agent', '''Mozilla/6.0 (iPhone; CPU iPhone OS 8_0like Mac OS X)
               AppleWebKit/536.26 (KHTML, like Gecko)
               Version/8.0Mobile/10A5376e Safari/8536.25''')
with request.urlopen(req) as f:
    data = f.read()
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', data.decode('utf-8'))
